import QQmapWX from '../../../libs/qqmap-wx-jssdk.min'
import Schema from 'async-validator'
import { toast } from '../../../../../utils/extendApi'
import { reqAddAddress, reqUpdateAddress, reqAddressInfo } from '../../../api/address'

Page({
  // 页面的初始数据
  data: {
    name: '', //收货人
    phone: '', //手机号码
    provinceName: '', //省
    provinceCode: '', //省编码
    cityName: '', //市
    cityCode: '', //市编码
    districtName: '', //区
    districtCode: '', //市编码
    address: '', //详细地址
    fullAddress: '', //完整地址
    isDefault: 0
  },
  //获取定位
  async onLocation() {
    const { latitude, longitude, name } = await wx.chooseLocation()
    this.qqmapwx.reverseGeocoder({
      location: {
        longitude,
        latitude
      },
      success: (res) => {
        //获取地址
        const { adcode, province, city, district } = res.result.ad_info
        //获取街道门牌
        const { street, street_number } = res.result.address_component
        //获取标准地址
        const { standard_address } = res.result.formatted_addresses

        this.setData({
          provinceName: province,
          provinceCode: adcode.replace(adcode.substring(2, 6), '0000'),
          cityName: city,
          cityCode: adcode.replace(adcode.substring(4, 6), '00'),
          districtName: district,
          districtCode: district && adcode,
          address: street + street_number + name,
          fullAddress: standard_address + name
        })
      }
    })
  },
  // 保存收货地址
  async saveAddrssForm(event) {
    const { provinceName, cityName, districtName, address } = this.data
    const params = {
      ...this.data,
      fullAddress: provinceName + cityName + districtName + address,
      isDefault: this.data.isDefault ? 1 : 0
    }
    const { valid } = await this.validatorAddress(params)
    if (!valid) {
      return
    }
    const res = this.addressId
      ? await reqUpdateAddress(params)
      : await reqAddAddress(params)
    console.log(res)
    if (res.code === 200) {
      wx.navigateBack({
        success: () => {
          toast({
            title: this.addressId ? '更新收货地址成功' : '新增收货地址成功'
          })
        }
      })
    }
  },
  validatorAddress(params) {
    //验证收货人，是否只包含大小写字母、数字和中文字符
    const nameRegExp = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$'
    //验证手机号，是否符合中国大陆手机号码的格式
    const phoneReg = '^1[2-9]\\d{9}$'
    const rules = {
      name: [
        { required: true, message: '请输入收货人姓名' },
        { pattern: nameRegExp, message: '收货人姓名不合法' }
      ],
      phone: [
        { required: true, message: '请输入收货人手机号' },
        { pattern: phoneReg, message: '收货人手机号不合法' }
      ],
      provinceName: { required: true, message: '请选择收货人所在地区' },
      address: { required: true, message: '请输入详细地址' }
    }
    const validator = new Schema(rules)

    return new Promise((resolve) => {
      validator.validate(params, (errors) => {
        if (errors) {
          toast({ title: errors[0].message })
          resolve({ valid: false })
        } else {
          resolve({ valid: true })
        }
      })
    })
  },
  // 省市区选择
  onAddressChange(event) {
    const [provinceName, cityName, districtName] = event.detail.value
    const [provinceCode, cityCode, districtCode] = event.detail.code
    this.setData({
      provinceName,
      cityName,
      districtName,
      provinceCode,
      cityCode,
      districtCode
    })
  },
  async showAddressInfo(id) {
    this.addressId = id
    wx.setNavigationBarTitle({
      title: '更新收货地址'
    })
    const { data } = await reqAddressInfo(id)
    this.setData(data)
  },
  onLoad(options) {
    this.qqmapwx = new QQmapWX({
      key: '7ILBZ-YB56U-IFYVH-GFCNL-XHHDQ-IDFSS'
    })
    if (options.id) {
      this.showAddressInfo(options.id)
    }
  }
})
